<template>
	<div style="background-color: white;">
		<a-row :gutter="20" justify="end">
			<a-col :span="2" class="py-4 text-center">
				<a-space>
					<a-button @click="closeTab('/plan')">
						<close-outlined />关闭
					</a-button>
				</a-space>
			</a-col>
		</a-row>
		<h2 style="text-align: center;padding: 12px">{{ planInfo.project?.name }}总控计划表</h2>
		<div style="padding: 12px;" class="flex">
			<div class="flex-auto">计划编号： {{ planInfo.code }}</div>
			<div class="flex-auto">计划制定人： {{ planInfo.opr_user?.fullname }}</div>
		</div>
		<div style="padding: 12px;">
			<a-button v-permission="16" type="primary" style="margin-right: 6px;" @click="router.push(`/plan/create?parent_id=${planId}`)">创建新的总控计划</a-button>
			<a-button v-permission="26" type="primary" style="margin-right: 6px;" @click="router.push(`/plan/summary/${planId}`)">总控计划汇总</a-button>
			<a-button v-permission="27" type="primary" @click="router.push(`/plan/summarygh/${planId}?project_id=${planInfo.project?.id}`)">工号计划汇总</a-button>
		</div>
		<a-table :expand-icon="expandIcon" row-key="id" :expanded-row-keys="expandedRowKeys" :pagination="pagination" :data-source="dataSource" :columns="columns" @expand="handleExpand" @change="initData">
			<template #bodyCell="{ column, record }">
				<template v-if="column.key === 'operation'">
					<a-button v-permission="20" type="link" target="_blank" @click="router.push(`/plan/detailinfo/${record.id}`);">查看</a-button>

					<template v-if="![0,1,2].includes(record.workflow_status)">
						<a-button v-permission="21" type="link" @click="router.push(`/plan/edit/${record.id}?parent_id=${planId}`);">
							<EditOutlined />修改
						</a-button>
						<a-button v-permission="100" type="link" style="color:#ff7875" @click="deletePlan(record.id)">
							<DeleteOutlined />删除
						</a-button>
					</template>
				</template>
				<template v-else-if="column.key === 'flowStatus'">
					<div>
						<div v-if="record.flow_status === 2">已完成</div>
						<flow-model v-else :module-id="'plan'" :item-id="record.id" @change="changeFlowStatusData2"></flow-model>
					</div>
				</template>
				<template v-else-if="column.key === 'workflow_status'">
					<div>
						<a-workflow type="status" module="plan" :status="record.workflow_status" />
					</div>
				</template>
			</template>
			<template #expandedRowRender="{ record }">
				<a-table :columns="innerColumns" :data-source="record.materials" :pagination="false"></a-table>
			</template>
		</a-table>
	</div>
</template>

<script setup lang="jsx">
import { EditOutlined, DeleteOutlined, CaretUpOutlined, CaretDownOutlined, CloseOutlined } from "@ant-design/icons-vue";
import { usePagination } from "vue-request";
import { ref, inject, computed, getCurrentInstance, watch, reactive } from "vue";
import { post } from "../utils";
import dayjs from "dayjs";

import { useRoute, useRouter } from "vue-router";
import { AWorkflow } from "@/components/index.js";
const route = useRoute();
const router = useRouter();

const planId = computed(() => {
	return route.params.id || 0;
});

const expandIcon = ({ expanded, onExpand, record }) => {

	return (<span onClick={e => onExpand(record, e)} style={{ cursor: 'pointer', marginRight: '8px' }}>
		{expanded ? <CaretUpOutlined /> : <CaretDownOutlined />}
	</span>)


}


const columns = [
	{
		title: "序号",
		dataIndex: "id",

	},
	{
		title: "计划名称",
		dataIndex: "name",
		width: 230,
		// align: 'center'
	},
	{
		title: "计划编号",
		dataIndex: 'code',
		align: 'center'
	},

	{
		title: "创建时间",
		dataIndex: "create_time",
		customRender: ({ text }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		},
		align: 'center'
	},
	{
		title: "创建人",
		dataIndex: "opr_user",
		customRender: ({ text }) => {
			return text?.fullname || text?.username;
		}
	},
	// {
	// 	title: "状态",
	// 	dataIndex: "state",
	// 	customRender: ({ text }) => {
	// 		return text === 1 ? "待审核" : "Unknown";
	// 	},
	// },
	{
		title: "状态",
		//dataIndex: "status",
		key: "workflow_status",
		sorter: false,
		width: 70,
		ellipsis: true
	},
	{
		title: "操作",
		dataIndex: "operation",
		key: "operation",
		width: 150,
		fixed: "right"
	}
];
const searchState = reactive({ ids: '' });

const pointData = ref([]);
const planInfo = ref({});

//构建工号
post("plan/info", { id: planId.value }).then(data => {
	planInfo.value = data;
	
	post("department/info", {
		id: planInfo.value.project?.id,
		...searchState
	}).then(d => {
		//获取工号
		pointData.value = d.pointData;
	});
});

/*
const changeflowStatus = e => {
	if (e && searchState) {
		searchState.ids = e.ids;
		if (searchState.ids) {
			
		}
	}
};
*/

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };

	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};

const innerColumns = computed(() => {
	const columns = [
		{
			title: "材料名称",
			dataIndex: "name",
			width: 150,
			extra: 0
		},
		{
			title: "材料规格",
			dataIndex: "model",
			width: 150,
			extra: 0
		},
		{
			title: "单位",
			dataIndex: "unit",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "数量",
			dataIndex: "quantity",
			width: 120,
			extra: 0,
			align: "center"
		}
	];
	pointData.value.forEach((p, i) => {
		columns.push({
			title: p.name,
			dataIndex: p.id,
			align: "center",
			width: 120
		});
	});

	return columns;
});

const { data, current, run, pageSize, total } = usePagination(params => post("plan", { type: 1, parent_id: planId.value, ...params }), {
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

const expandedRowKeys = ref([]);
const handleExpand = (expanded, record) => {
	if (expanded) {
		expandedRowKeys.value.push(record.id);
	} else {
		const index = expandedRowKeys.value.findIndex(key => key === record.id);
		if (index > -1) {
			expandedRowKeys.value.splice(index, 1);
		}
	}
};

const dataSource = ref([]);
watch(data, newVal => {
	if (newVal && newVal.data) {
		dataSource.value = newVal.data
			.map(item => {
				const projectMaterials = item.projectMaterials;
				item.materials = item.materials?.map(material => {
					const jobNos = projectMaterials
						.filter(target => target.material_id === material.id)
						.reduce((res, curr) => {
							res[curr.gonghao_id] = curr.gonghao_qty;
							return res;
						}, {});
					return {
						...material,
						...jobNos,
						...material.PlanMaterial
					};
				});
				return item;
			})
			.sort((a, b) => a.id - b.id);
	}
});

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const { proxy } = getCurrentInstance();
const deletePlan = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的计划吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("plan/delete", { id })
				.then(() => {
					proxy.$message.success("计划删除成功");
					run();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		}
	});
};

const changeFlowStatusData2 = () => {}
const closeTab = inject("closeTab");
</script>

<style scoped lang="scss"></style>